home *** CD-ROM | disk | FTP | other *** search
- Path: amaryllisp1.appsig.com!user
- From: larry_kearney@appsig.com (Lawrence Kearney)
- Newsgroups: comp.lang.c
- Subject: Re: help with pi algorithm
- Date: Tue, 23 Jan 1996 13:15:38 -0700
- Organization: Applied Signal Technology
- Message-ID: <larry_kearney-2301961315380001@amaryllisp1.appsig.com>
- References: <0fc_9601240111@csource.blaze.net.au>
- NNTP-Posting-Host: amaryllisp1.appsig.com
-
- > I am a newbie C programmer trying to write an algorithm to work out the
- > value of pi fairly accurately. I have written the following code, but I'm
- > not sure whether it's considered 'nasty' programming, or whether it could
- > be written to run more quickly.
- >
- > #include <stdio.h>
- > main()
- > {
- > long double pi = 0;
- > long int = count;
- > for (count = 1; count <= 300000; count += 4) {
- > pi += 4.0 / count; pi -= 4.0 / (count + 2);
- > }
- > printf("Value of pi is approx %.19Lf)", pi);
- > return 0;
- > }
- >
- > Any comments please???
-
- The algorithm you've chosen is a poor one in that it will converge to pi
- very, very, slowly (in, in fact, it converges at all. I don't know as I
- haven't tested it). Rather than trying to speed this one up, I would
- suggest that you invest some time looking for one that converges at a
- faster rate.
-
- If you insist on using this algorithm, I would suggest that you keep all
- the values in your computation as long doubles rather than making the
- compiler continually convert long ints to long doubles, a very expensive
- process. You don't need to tie count to the loop variable, just create a
- separate variable for the loop index.
-
- This concept of finding better algorithms instead of spending time
- optimizing poor ones is true in a large number of cases. Although yours is
- a simple case and is intended to help you learn how to program in C, as
- you become more experienced and find yourself attempting to write fast,
- efficient programs, you'll find that it applies more and more.
-
- --
- Larry Kearney | "You want fries with that?"
- Applied Signal Technology |
- larry_kearney@appsig.com |
-